package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;

import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: AddressServiceImpl
 * @author: ZK
 * @data: 2020/3/7 14:27
 * @Description:
 */

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;
    //新增地址
    @Override
    public void add(Address address) {
        addressDao.add(address);
    }

    //查询所有地址
    @Override
    public List<Address> findAll() {
        return addressDao.findAll();
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage, pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Address> page = addressDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

   /* @Override
    public void delete(Integer id) {

    }*/

    //根据id删除检查项
    @Override
    public void delete(Integer id) {
        long count = addressDao.selectCountByOrderId(id);
        if (count > 0) {
            //已经被关联，不能删除

                new RuntimeException(MessageConstant.DELETE_CHECKITEM_FAIL);

        } else {
            //可以删除
            addressDao.deleteById(id);
        }
    }

    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    //
    @Override
    public PageResult pageQyery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> page = addressDao.findByCondition(queryString);
        long total = page.getTotal();
        List<Address> rows = page.getResult();

        return new PageResult(total, rows);
    }

    /*编辑*/
    @Override
    public void edit(Address address) {
        addressDao.edit(address);
    }

}